{% extends 'base.html' %}
{% load static %}

{% block title %}
    编辑文章
{% endblock %}


{% block content %}
	<!-- section main content -->
        <section class="main-content mt-3">
            <div class="container-xl">
                <div class="row">
                    <div class="col-md-8">
                        <!-- 博客编辑区域 -->
                        <div class="post-editor rounded bordered padding-30">
                            <div class="mb-4">
                                <input type="text" class="form-control form-control-lg" placeholder="输入文章标题..." id="post-title">
                            </div>

                            <div id="editor"></div>

                            <div class="mt-4">
                                <label class="form-label">文章标签</label>
                                <div class="form-control form-control-tag" id="tags-container">
                                    <input type="text" id="tag-input" placeholder="输入标签后按回车..." style="border:none;outline:none;width:150px;">
                                </div>
                            </div>

                            <div class="post-cover-upload mt-4" id="cover-upload">
                                <i class="icon-picture" style="font-size: 48px; color: #6c757d;"></i>
                                <h4 class="mt-3 mb-2">点击上传封面图片</h4>
                                <p class="text-muted">支持 jpg、png 格式，建议尺寸 1200x800</p>
                                <input type="file" id="cover-input" accept="image/*" style="display: none;">
                                <img id="cover-preview" class="post-cover-preview">
                            </div>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <!-- 发布选项 -->
                        <div class="publish-options">
                            <h4 class="mb-4">发布选项</h4>

                            <div class="mb-3">
                                <label class="form-label">分类</label>
                                <select class="form-select" id="post-category">
                                    <option value="">选择分类...</option>
                                    <option value="1">生活方式</option>
                                    <option value="2">灵感</option>
                                    <option value="3">时尚</option>
                                    <option value="4">文化</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">摘要</label>
                                <textarea class="form-control" rows="4" placeholder="输入文章摘要..."></textarea>
                            </div>

                            <div class="mb-3">
                                <div class="d-flex justify-content-between">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="allowComments" checked>
                                        <label class="form-check-label" for="allowComments">允许评论</label>
                                    </div>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="privatePost">
                                        <label class="form-check-label" for="privatePost">仅我可见</label>
                                    </div>
                                </div>
                            </div>

                            <div class="d-grid gap-2">
                                <button class="btn btn-publish" type="button">发布文章</button>
                                <button class="btn btn-draft" type="button">保存草稿</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
{% endblock %}


{% block js %}
	<!-- CKEditor 5 -->
    <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
    <script>
        let editor;
        let coverImageUrl = ''; // 保存封面图片URL

        // 初始化 CKEditor
        ClassicEditor
            .create(document.querySelector('#editor'), {
                toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'outdent', 'indent', '|', 'imageUpload', 'blockQuote', 'insertTable', 'mediaEmbed', 'undo', 'redo'],
                language: 'zh-cn',
                // 配置图片上传
                simpleUpload: {
                    uploadUrl: 'http://192.168.57.182:8899/upload',
                    headers: {
                        'Accept': 'application/json'
                    }
                }
            })
            .then(newEditor => {
                editor = newEditor;
            })
            .catch(error => {
                console.error(error);
            });

        // 封面图片上传预览和上传处理
        document.getElementById('cover-upload').addEventListener('click', () => {
            document.getElementById('cover-input').click();
        });

        document.getElementById('cover-input').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                // 预览
                const reader = new FileReader();
                reader.onload = (e) => {
                    const preview = document.getElementById('cover-preview');
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(file);

                // 上传
                const formData = new FormData();
                formData.append('file', file);

                $.ajax({
                    url: '/life/image_upload/',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        coverImageUrl = response.url; // 假设接口返回 {url: "图片URL"}
                        console.log('封面图片上传成功:', coverImageUrl);
                    },
                    error: function(xhr, status, error) {
                        alert('封面图片上传失败，请重试');
                        console.error('上传失败:', error);
                    }
                });
            }
        });

        // 标签管理
        const tagsContainer = document.getElementById('tags-container');
        const tagInput = document.getElementById('tag-input');
        let tags = [];

        function addTag(tag) {
            if (tag && !tags.includes(tag)) {
                tags.push(tag);
                const tagElement = document.createElement('span');
                tagElement.className = 'tag-item';
                tagElement.innerHTML = `${tag}<span class="remove-tag">×</span>`;
                tagElement.querySelector('.remove-tag').addEventListener('click', () => {
                    tags = tags.filter(t => t !== tag);
                    tagElement.remove();
                });
                tagsContainer.insertBefore(tagElement, tagInput);
            }
            tagInput.value = '';
        }

        tagInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                addTag(tagInput.value.trim());
            }
        });

        // 发布文章
        function publishPost(isDraft = false) {
            const title = $('#post-title').val();
            const content = editor.getData();
            const category = $('#post-category').val();
            const summary = $('textarea').val();
            const allowComments = $('#allowComments').is(':checked');
            const isPrivate = $('#privatePost').is(':checked');

            // 表单验证
            if (!title.trim()) {
                alert('请输入文章标题');
                return;
            }
            if (!content.trim()) {
                alert('请输入文章内容');
                return;
            }
            if (!category) {
                alert('请选择文章分类');
                return;
            }
            if (!coverImageUrl) {
                alert('请上传封面图片');
                return;
            }

            // 准备发送的数据
            const postData = {
                title: title,  // 标题
                body: content,  // 内容
                fm_image: coverImageUrl,  // 封面图片
                category: category,  // 分类
                desc: summary,  // 摘要
                tags: tags,  // 标签
                allowComments: allowComments,  // 是否允许评论
                isPrivate: isPrivate,  // 是否私密 - 仅我可见
                status: isDraft ? '2' : '1'  // 状态 草稿-2|已发表-1
            };

            // 发送请求
            $.ajax({
                url: '/life/publish/',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(postData),
                success: function(response) {
                    if (isDraft) {
                        alert('草稿保存成功！');
                    } else {
                        alert('文章发布成功！');
                    }
                    // 可以根据需要跳转到文章列表或预览页面
                    window.location.href = '/';
                },
                error: function(xhr, status, error) {
                    alert(isDraft ? '草稿保存失败，请重试' : '文章发布失败，请重试');
                    console.error('发布失败:', error);
                }
            });
        }

        // 发布按钮点击事件
        document.querySelector('.btn-publish').addEventListener('click', () => {
            publishPost(false);
        });

        // 保存草稿按钮点击事件
        document.querySelector('.btn-draft').addEventListener('click', () => {
            publishPost(true);
        });
    </script>
{% endblock %}

{% block css %}
	<style>
        @media (min-width: 1400px) {
            .container-xl {
                max-width: 1600px;
            }
        }
        .ck-editor__editable {
            min-height: 400px;
            max-height: 600px;
        }
        .post-cover-upload {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .post-cover-upload:hover {
            border-color: #fe5e74;
            background: #fff;
        }
        .post-cover-preview {
            max-width: 100%;
            max-height: 300px;
            margin-top: 20px;
            border-radius: 10px;
            display: none;
        }
        .form-control-tag {
            height: auto;
            padding: 0.5rem;
        }
        .tag-item {
            display: inline-block;
            background: #fe5e74;
            color: white;
            padding: 2px 8px;
            border-radius: 15px;
            margin: 2px 4px;
            font-size: 14px;
        }
        .tag-item .remove-tag {
            margin-left: 5px;
            cursor: pointer;
        }
        .publish-options {
            background: #fff;
            border: 1px solid #dee2e6;
            border-radius: 10px;
            padding: 20px;
        }
        .btn-publish {
            background: #fe5e74;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-publish:hover {
            background: #e54d63;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(254, 94, 116, 0.2);
        }
        .btn-draft {
            background: #6c757d;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-draft:hover {
            background: #5a6268;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.2);
        }
    </style>
{% endblock %}





